package com.telit.uav.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.telit.uav.dao.AppUavTrackDetailDao;
import com.telit.uav.dao.CommUavDao;
import com.telit.uav.dao.FlightDetailsDao;
import com.telit.uav.dto.UavFlyRecordDTO;
import com.telit.uav.entity.AppUavTrackDetail;
import com.telit.uav.entity.CommUav;
import com.telit.uav.service.FlightDetailsService;
import com.telit.upms.vo.MicroSysUserAllInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author:zhangwei
 * @Description:
 * @Time:Created on 2021/9/18 8:10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FlightDetailsServiceImpl implements FlightDetailsService {

    @Autowired
    FlightDetailsDao flightDetailsDao;

    @Autowired
    AppUavTrackDetailDao appUavTrackDetailDao;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private CommUavDao commUavDao;

    @Override
    public Map<String, Object> getTimeAxisByTaskIdAndUseId(Long taskId, Long userId) {
        String taskStatus = flightDetailsDao.selectTaskStatusByTaskId(taskId);
        Map<String, Object> map = new HashMap<String, Object>();
        if ("3".equals(taskStatus)) {//已完成
            map = flightDetailsDao.selectTimeAxisByEnd(taskId);
        } else if ("2".equals(taskStatus)) {//执行中
            map = flightDetailsDao.selectTimeAxisByOngoing(taskId, userId);
        } else {
            return null;
        }
        map.put("taskStatus", taskStatus);
        return map;
    }

    /**
     * 根据任务id、userId获取飞行轨迹信息
     *
     * @param taskId
     * @param userId
     * @return
     */
    @Override
    public List<AppUavTrackDetail> listUavTrackDetail(Long taskId, Long userId) {
        return flightDetailsDao.selectUavTrackDetail(taskId, userId);
    }

    @Override
    public List<AppUavTrackDetail> queryTrackDetail(Long taskId, Long userId) {
        return flightDetailsDao.queryTrackDetail(taskId, userId);
    }

    /**
     * 分页条件查询飞行记录列表
     *
     * @param current
     * @param size
     * @param uavFlyRecordDTO
     * @return
     */
    @Override
    public IPage<UavFlyRecordDTO> listFlyRecordByPage(Integer current, Integer size, UavFlyRecordDTO uavFlyRecordDTO) {
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------start
       /* IPage<UavFlyRecordDTO> uavFlyRecordDTOIPage = new Page<>(current, size);
        uavFlyRecordDTOIPage = flightDetailsDao.selectFlyRecordByPage(uavFlyRecordDTOIPage, uavFlyRecordDTO);
        List<UavFlyRecordDTO> uavFlyRecords = uavFlyRecordDTOIPage.getRecords();
        List<UavFlyRecordDTO> uavFlyRecordList = new ArrayList<UavFlyRecordDTO>();
        for (UavFlyRecordDTO uavFlyRecord : uavFlyRecords) {
            SysUserDetailVo sysUserVo = userInfoService.getUserInfo(uavFlyRecord.getUserId());
            if (sysUserVo != null) {
//                uavFlyRecord.setUavUserName(sysUserVo.getRealName());
                uavFlyRecord.setUavUserName(sysUserVo.getRealName());
            }
            CommUav commUav = commUavDao.queryUavInfoByUavName(uavFlyRecord.getUavName());
            int isFlying = commUav == null ? 0 : commUav.getIsFlying();
//            uavFlyRecord.setFlyStatus((isFlying==1)?"飞行中":"已完成");
            if (isFlying == 1) {//无人机在飞行中,根据taskId状态判断哪个任务在飞行中，taskId状态在执行中，则在飞行中
                String taskStatus = flightDetailsDao.selectTaskStatusByTaskId(uavFlyRecord.getTaskId());
                uavFlyRecord.setFlyStatus(("2".equals(taskStatus)) ? "飞行中" : "已完成");
            } else {//无人机不在飞行，所有都为已完成状态
                uavFlyRecord.setFlyStatus("已完成");
            }
            uavFlyRecord.setEndTime(timePastSecond(uavFlyRecord.getStartTime(), Integer.parseInt(uavFlyRecord.getFlyTime())));
            uavFlyRecord.setFlyTime(minuteAndSecond(Integer.parseInt(uavFlyRecord.getFlyTime())));
            String maxHeight = flightDetailsDao.selectMaxHeight(uavFlyRecord.getTaskId(), uavFlyRecord.getUserId());
            uavFlyRecord.setMaxHigh(maxHeight);

            uavFlyRecordList.add(uavFlyRecord);
        }

        uavFlyRecordDTOIPage.setRecords(uavFlyRecordList);

        return uavFlyRecordDTOIPage;*/

        IPage<UavFlyRecordDTO> uavFlyRecordDTOIPage = new Page<>(current, size);
        uavFlyRecordDTOIPage = flightDetailsDao.selectFlyRecordByPage(uavFlyRecordDTOIPage, uavFlyRecordDTO);
        List<UavFlyRecordDTO> uavFlyRecords = uavFlyRecordDTOIPage.getRecords();
        List<UavFlyRecordDTO> uavFlyRecordList = new ArrayList<UavFlyRecordDTO>();
        final Map<Long, MicroSysUserAllInfoVo> idMapping = Maps.newHashMap();
        if (CollUtil.isNotEmpty(uavFlyRecords)) {
            idMapping.putAll(userInfoService.findAndConvertUserInfoByIdsEndWithVo(
                    uavFlyRecords.stream().map(UavFlyRecordDTO::getUserId).collect(Collectors.toList())
            ));
        }
        for (UavFlyRecordDTO uavFlyRecord : uavFlyRecords) {
            final MicroSysUserAllInfoVo sysUserVo = idMapping.get(uavFlyRecord.getUserId());
            if (sysUserVo != null) {
//                uavFlyRecord.setUavUserName(sysUserVo.getRealName());
                uavFlyRecord.setUavUserName(sysUserVo.getRealName());
            }
            CommUav commUav = commUavDao.queryUavInfoByUavCode(uavFlyRecord.getUavCode());
            int isFlying = commUav == null ? 0 : commUav.getIsFlying();
//            uavFlyRecord.setFlyStatus((isFlying==1)?"飞行中":"已完成");
            if (isFlying == 1) {//无人机在飞行中,根据taskId状态判断哪个任务在飞行中，taskId状态在执行中，则在飞行中
                String taskStatus = flightDetailsDao.selectTaskStatusByTaskId(uavFlyRecord.getTaskId());
                uavFlyRecord.setFlyStatus(("2".equals(taskStatus)) ? "飞行中" : "已完成");
            } else {//无人机不在飞行，所有都为已完成状态
                uavFlyRecord.setFlyStatus("已完成");
            }
            //uavFlyRecord.setEndTime(timePastSecond(uavFlyRecord.getStartTime(), Integer.parseInt(uavFlyRecord.getFlyTime())));
            uavFlyRecord.setFlyTime(minuteAndSecond(Integer.parseInt(uavFlyRecord.getFlyTime())));
            String maxHeight = flightDetailsDao.selectMaxHeight(uavFlyRecord.getTaskId(), uavFlyRecord.getUserId());
            uavFlyRecord.setMaxHigh(maxHeight);

            uavFlyRecordList.add(uavFlyRecord);
        }

        uavFlyRecordDTOIPage.setRecords(uavFlyRecordList);

        return uavFlyRecordDTOIPage;
        //2022-05-18 优化 避免过度请求 -------fixed by yzx-------start
    }

    public static Date timePastSecond(Date dt, int seconds) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date dt=sdf.parse(otime);

            Calendar newTime = Calendar.getInstance();
            newTime.setTime(dt);
            newTime.add(Calendar.SECOND, seconds);//日期加10秒

            Date dt1 = newTime.getTime();
            String retval = sdf.format(dt1);

            return sdf.parse(retval);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static String minuteAndSecond(int seconds) {
        int temp = 0;
        StringBuffer sb = new StringBuffer();
        //计算小时
//        temp = seconds/3600;
//        sb.append((temp<10)?"0"+temp+":":""+temp+":");
        //分钟
        temp = seconds / 60;
        sb.append((temp < 10) ? "0" + temp + "分钟" : "" + temp + "分钟");

        //秒
        temp = seconds % 60;
        sb.append((temp < 10) ? "0" + temp + "秒" : "" + temp + "秒");

        return sb.toString();
    }


}
